<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Goods extends Promotion
{
    use SoftDeletes;
    protected $guarded = [];
    protected $casts = [
        'is_hot' => 'boolean',
        'is_best' => 'boolean',
        'is_new' => 'boolean',
        'is_on_sale' => 'boolean',
        'is_shipping' => 'boolean',
        'is_virtual' => 'boolean',
        'is_exchange' => 'boolean',
        'price' => 'double',
        'original_price' => 'double',
        'full_cut' => 'array'
    ];

    public function setFullCutAttribute($value)
    {
        if (is_array($value) && count($value) > 0) {
            $value = array_values(arraySort($value, 'amount', 'desc', true));
        } else {
            $value = NULL;
        }
        $this->attributes['full_cut'] = $value ? json_encode($value) : NULL;
    }

    public function content()
    {
        return $this->hasOne('App\GoodsContent');
    }

    public function category()
    {
        return $this->belongSTo('App\Category');
    }

    public function attrs()
    {
        return $this->belongsToMany('App\Attr');
    }

    public function attachments()
    {
        return $this->morphMany('App\Attachment', 'attachmentable');
    }

    public function specPrices()
    {
        return $this->hasMany('App\SpecGoodsPrice');
    }

    public function getThumbImgAttribute($value)
    {
        if (strpos(url()->current(),'edit') === false) {
            return asset('storage/'.$value);
        }
        return $value;
    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    // 限时秒杀
    public function flashSale()
    {
        return $this->hasOne('App\FlashSale');
    }
    // 拼团
    public function teamActivity()
    {
        return $this->hasOne('App\TeamActivity');
    }
}
